import EventManager from "../manager/EventManager";

const { ccclass, property } = cc._decorator;

@ccclass
export default class BaseWindow extends cc.Component {
    /**需要过滤的name,主要是过滤预制体，防止重复判断，也可以不加，不加的话，就必须保证绑定的key整个界面唯一，否则会覆盖掉*/
    public exclude: string[] = [];
    /**
     * btn_xx 按钮
     * sp_xx 精灵
     * lb_xx 文本
     * ani_xx animation
     * spine_xx spine动画
     * ...cc.Node
     */
    onLoad() {
        this.bindComponent(this.node);
        this.initNetResp();
        this.addListener();
    }
    addListener(){

    }
    removeListener(){

    }
    bindComponent(node: cc.Node) {
        let key = node["_name"]
        // console.log("name:" + key);
        if (this[node["_name"]] === null) {
            this[node["_name"]] = node;
            if (key.indexOf("btn_") == 0) {
                this[node["_name"]] = node.getComponent(cc.Button);
            } else if (key.indexOf("sp_") == 0) {
                this[node["_name"]] = node.getComponent(cc.Sprite);
            } else if (key.indexOf("lb_") == 0) {
                this[node["_name"]] = node.getComponent(cc.Label);
            } else if (key.indexOf("ani_") == 0) {
                this[node["_name"]] = node.getComponent(cc.Animation);
            } else if (key.indexOf("spine_") == 0) {
                this[node["_name"]] = node.getComponent(sp.Skeleton);
            }
        }
        if (this.exclude.indexOf(key) != -1) return;
        let children = node.children;
        for (let i = 0, len = node.childrenCount; i < len; i++) {
            this.bindComponent(children[i]);
        }
    }
    initNetResp() {
        for (let attrName in this) {
            let pattern = /^_resp_/;
            if (pattern.test(attrName) == true) {
                let eventName = attrName.substr(6);
                if (eventName) {
                    EventManager.Inst.on(eventName, this, this[attrName]);
                }
            }
        }
    }
    onDestroy() {
        this.removeListener();
        EventManager.Inst.offAll(this);
    }
}